//
//  MCVIPCenterViewController.m
//  TLYL
//
//  Created by MC on 2017/11/22.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCVIPCenterViewController.h"
#import "MCVIPCenterHeaderView.h"
#import <MJRefresh/MJRefresh.h>
#import "UINavigationBar+Awesome.h"
#import "MCMineCellModel.h"
#import "MCVIPCenterTableViewCell.h"
#import "MCAllLevelVipViewController.h"
#import "MCGetUserVipInfoModel.h"
#import "MCVipCenterMoreNavView.h"
#import "MCPopAlertView.h"
#import "MCKefuViewController.h"

//vip分 非vip  和  vip，显示这块统一下
//非vip的界面显示的都 --
//vip的界面专属客服和域名，有显示有，无显示无。后面会配置专属客服链接，是可访问的
#define MInAlpha   0.01
#define NAVCOLOR   MC_THEME_COLOR;
#define NAVBAR_CHANGE_POINT 10

@interface MCVIPCenterViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
MCVIPCenterHeaderViewDelegate,
MCVIPCenterTableViewCellDelegate
>
typedef void(^MCVIPCenterViewControllerCompeletion)(BOOL result, NSDictionary *data );

/**headerView*/
@property (nonatomic,strong)MCVIPCenterHeaderView * headerView;
/**tableView*/
@property(nonatomic, strong)UITableView *tableView;
/**sectionMarr*/
@property(nonatomic, strong)NSMutableArray*sectionMarr;

@property(nonatomic, strong)UIView *navBgView;
/*
 * Api数据模型
 */
@property(nonatomic, strong)MCGetUserVipInfoModel * getUserVipInfoModel;
@property(nonatomic, strong)MCGetUserVipInfoDataModel * dataSource;

@property(nonatomic, strong)ExceptionView * exceptionView;

@property(nonatomic, strong)UIView *cloverView;

@property(nonatomic, strong)MCVipCenterMoreNavView * moreNavView;

@property(nonatomic, assign)BOOL isShowMoreBtn;
@end

@implementation MCVIPCenterViewController

#pragma mark - life cycle

- (void)viewDidLoad {
    
    [super viewDidLoad];

    [self setProperty];
    
    [self createUI];
    
    [self createSectionMarr];
    
    [self loadData];
}


- (void)setNavBar{
    
    UIView *navBgView = [[UIView alloc] initWithFrame:CGRectMake(100, 0, G_SCREENWIDTH-100, kStatusBarAndNavigationBarHeight)];
    [self.navigationController.navigationBar addSubview:navBgView];
    self.navBgView = navBgView;
    navBgView.backgroundColor = [UIColor clearColor];
    
    
    UILabel * labTitle=[[UILabel alloc]initWithFrame:CGRectMake(0, 7, G_SCREENWIDTH-200, 30)];
    labTitle.text=@"VIP等级";
    labTitle.font=[UIFont systemFontOfSize:18];
    labTitle.textColor=[UIColor whiteColor];
    labTitle.textAlignment=NSTextAlignmentCenter;
    
    UIButton * settingBtn=[[UIButton alloc]init];
    [settingBtn setImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    settingBtn.frame=CGRectMake(G_SCREENWIDTH-100-18-22, 11, 22, 22);
    [settingBtn addTarget:self action:@selector(openMoreFuLiorGuiZe) forControlEvents:UIControlEventTouchUpInside];
    

#pragma mark 这部是关键
    [navBgView addSubview:labTitle];
    [navBgView addSubview:settingBtn];
    
    
}

#pragma mark-@protocol UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    UIColor * color = NAVCOLOR;
    CGFloat offsetY = scrollView.contentOffset.y ;
    if (offsetY > NAVBAR_CHANGE_POINT) {
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + kStatusBarAndNavigationBarHeight - offsetY) / kStatusBarAndNavigationBarHeight));
        if (alpha<MInAlpha) {
            alpha=MInAlpha;
        }
#pragma mark HaveHiddenAnimation
        //begin
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        //end
        
        [self.navigationController.navigationBar vip_lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
        
        
    } else if(offsetY < 0 ){
#pragma mark HaveHiddenAnimation
        //begin
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        //        [self.navigationController setNavigationBarHidden:NO animated:YES];
        //end
        
        
        
        [self.navigationController.navigationBar vip_lt_setBackgroundColor:[color colorWithAlphaComponent:MInAlpha]];
    }else{
#pragma mark HaveHiddenAnimation
        //begin
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        //end
        
        [self.navigationController.navigationBar vip_lt_setBackgroundColor:[color colorWithAlphaComponent:MInAlpha]];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
  
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.navigationController.automaticallyAdjustsScrollViewInsets=NO;
        
    }
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    self.navigationController.navigationBar.translucent = YES;
    

    
    //设置当前控制器显示的title
    //    self.title = @" ";
    //设置tab显示的title
    
    
    //在下级页面有的需要隐藏当行栏-->所以在这显示出来
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.tableView.delegate = self;
    //取消导航栏最下面的那一条线
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
#pragma mark HaveHiddenAnimation ->当有隐藏和消失的动画时需要加这个(如无此效果,可全局搜索前面的英文定义进行删除,begin-->end ,不影响效果)
    //begin
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"white_7"] forBarMetrics:UIBarMetricsDefault];
    //end
    [self setNavBar];
    [self scrollViewDidScroll:self.tableView];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    MCPaySLBaseModel * dataSourceModel=[MCPaySLBaseModel sharedMCPaySLBaseModel];
    [dataSourceModel removeDataSource];
    
#pragma mark 这块我也不明白为什么取消了代理就好使了....
    self.tableView.delegate = nil;
    
    [self.navigationController.navigationBar lt_reset];
    [self.navBgView removeFromSuperview];
    [self.navigationController.navigationBar setShadowImage:nil];
    
}

#pragma mark==================setProperty======================
-(void)setProperty{
    //    Command选中点击进去发现，automaticallyAdjustsScrollViewInsets这个属性已经过期了
    //    而且是用了新属性contentInsetAdjustmentBehavior来代替。
    //    因此，要做个版本判断：
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.navigationController.automaticallyAdjustsScrollViewInsets=NO;
        
    }
    self.view.backgroundColor=RGB(231, 231, 231);
    _sectionMarr= [[NSMutableArray alloc]init];
}




#pragma mark==================createUI======================
-(void)createUI{
    
    _headerView=[[MCVIPCenterHeaderView alloc]init];
    _headerView.frame=CGRectMake(0, 0, G_SCREENWIDTH, [MCVIPCenterHeaderView computeHeight:nil]);
    _headerView.delegate=self;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.tableHeaderView = _headerView;
    [self.view addSubview:_tableView];
//    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self refreashData];
//    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(0);
        make.left.and.right.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];
    
    /*
     * 投注页右上角功能按钮
     */
    UIView *clover = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:clover];
    self.cloverView = clover;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCoverView)];
    [clover addGestureRecognizer:tap];
    clover.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.5];
    clover.hidden = YES;
    MCVipCenterMoreNavView * moreNavView=[[MCVipCenterMoreNavView alloc]init];
    [clover addSubview:moreNavView];
    moreNavView.frame=CGRectMake(G_SCREENWIDTH-90-10, kStatusBarAndNavigationBarHeight, 90, 0);
    _moreNavView=moreNavView;
    [_moreNavView.btn_Rule addTarget:self action:@selector(action_Rule) forControlEvents:UIControlEventTouchUpInside];
    [_moreNavView.btn_FLexplain addTarget:self action:@selector(action_FLexplain) forControlEvents:UIControlEventTouchUpInside];

}


-(void)loadData{
    [self.exceptionView dismiss];
    self.exceptionView = nil;
    [BKIndicationView showInView:self.view];
//UserID    是    String    当前登录用户 ID
    MCGetUserVipInfoModel * getUserVipInfoModel = [[MCGetUserVipInfoModel alloc]initWithDic:@{@"UserID":[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"]}];
    [getUserVipInfoModel refreashDataAndShow];
    self.getUserVipInfoModel = getUserVipInfoModel;
    __weak __typeof__ (self) wself = self;
    getUserVipInfoModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        wself.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
        wself.exceptionView.originY=kStatusBarAndNavigationBarHeight;
        ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
            [wself.exceptionView dismiss];
            wself.exceptionView = nil;
            [wself loadData];
        }];
        [wself.exceptionView addAction:action];
        [wself.exceptionView showInView:wself.view];
        
    };
    
    getUserVipInfoModel.callBackSuccessBlock = ^(id manager) {
        
        [wself setData:manager];
        
    };
    
}

-(void)setData:(NSDictionary *)dic{

    _dataSource = [MCGetUserVipInfoDataModel mj_objectWithKeyValues:dic];
    
    _headerView.dataSource=_dataSource;
    
    [self.tableView reloadData];
    
}

#pragma mark==================loadData======================
-(void)createSectionMarr{
    
    [_sectionMarr removeAllObjects];
    
    CellModel* model =[[CellModel alloc]init];
    model.reuseIdentifier = [NSString stringWithFormat:@"%@",NSStringFromClass([MCVIPCenterTableViewCell class])];
    model.className=NSStringFromClass([MCVIPCenterTableViewCell class]);
    model.height = [MCVIPCenterTableViewCell computeHeight:nil];
    model.selectionStyle=UITableViewCellSelectionStyleNone;
    model.accessoryType=UITableViewCellAccessoryNone;
    /*
     * 传递参数
     */
    model.userInfo = nil;
    
    SectionModel *model0=[SectionModel sectionModelWithTitle:@"" cells:@[model]];
    model0.headerhHeight=0.0001;
    model0.footerHeight=10;
    [_sectionMarr addObject:model0];
    [_tableView reloadData];
    
}


#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _sectionMarr.count;
}
//0               1      2     3      4       5      6
//非 VIP 用户    青铜    白银    黄金    铂金    钻石    王者
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _sectionMarr[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _sectionMarr[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _sectionMarr[section];
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [MCVIPCenterTableViewCell computeHeight:nil];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _sectionMarr[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    

    __weak __typeof(self)wself = self;
    
    if ([cm.className isEqualToString:NSStringFromClass([MCVIPCenterTableViewCell class])]) {
        
        MCVIPCenterTableViewCell *ex_cell=(MCVIPCenterTableViewCell *)cell;
        ex_cell.delegate=self;
        ex_cell.dataSource=_dataSource;
        
        ex_cell.allLevelBlock = ^{
            MCAllLevelVipViewController * vc = [[MCAllLevelVipViewController alloc]init];
            [wself.navigationController pushViewController:vc animated:YES];
        };
        
        ex_cell.keFuBlock = ^{
//            MCKefuViewController *vc = [[MCKefuViewController alloc] init];
//            [wself.navigationController pushViewController:vc animated:YES];
        };
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

-(void)goToAllLevelVipViewController{
    
    MCAllLevelVipViewController * vc=[[MCAllLevelVipViewController alloc]init];
    self.navigationController.navigationBarHidden=NO;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}

/*
 * 跳转界面
 */
-(void)goToVCWithType:(NSInteger )type{
    if (type==1001) {
        self.navigationController.navigationBarHidden=NO;
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)openMoreFuLiorGuiZe{
    if (_isShowMoreBtn) {
        _isShowMoreBtn=NO;
    }else{
        _isShowMoreBtn=YES;
    }
    
    
    [UIView animateWithDuration:0 animations:^{
    
        if (_isShowMoreBtn) {
            
            self.cloverView.hidden = NO;
            _moreNavView.frame=CGRectMake(G_SCREENWIDTH-90, kStatusBarAndNavigationBarHeight, 90, 90);
        }else{
            
            self.cloverView.hidden = YES;
            _moreNavView.frame=CGRectMake(G_SCREENWIDTH-90, kStatusBarAndNavigationBarHeight, 90, 0);
        }
    } completion:^(BOOL finished) {

    }];
}
- (void)tapCoverView{
    self.cloverView.hidden = YES;
    _isShowMoreBtn=NO;
}

-(void)action_Rule{
    [UIView animateWithDuration:0.2 animations:^{
        
        _moreNavView.frame=CGRectMake(G_SCREENWIDTH-90-10, kStatusBarAndNavigationBarHeight, 90, 0);
        
    } completion:^(BOOL finished) {
        
        self.cloverView.hidden = YES;
        MCPopAlertView *mcAlertView =[[MCPopAlertView alloc]initWithVIPType:MCPopAlertTypeVIPCenter_Rule Title:@"规则条款" leftBtn:@"朕知道了" rightBtn:nil];
        mcAlertView.resultIndex = ^(NSInteger index){
            _isShowMoreBtn=NO;
            if (index==1) {
            }
        };
        [mcAlertView showXLAlertView];
        

        
    }];
}

-(void)action_FLexplain{
    [UIView animateWithDuration:0.2 animations:^{
        
        _moreNavView.frame=CGRectMake(G_SCREENWIDTH-90-10, kStatusBarAndNavigationBarHeight, 90, 0);
        
    } completion:^(BOOL finished) {
        
        self.cloverView.hidden = YES;
        MCPopAlertView *mcAlertView =[[MCPopAlertView alloc]initWithVIPType:MCPopAlertTypeVIPCenter_FLExplain Title:@"福利说明" leftBtn:@"朕知道了" rightBtn:nil];
        
        mcAlertView.resultIndex = ^(NSInteger index){
            _isShowMoreBtn=NO;
            if (index==1) {
            }
        };
        [mcAlertView showXLAlertView];
    }];
}

- (void)cellDidSelectWithModel:(id *)model{
    
}
@end
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

